<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("流程分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('分类管理')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          class="learun-tree"
          ref="tree"
          node-key="id"
          :highlight-current="true"
          :data="dataItemTree_FlowSort"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="el-icon-notebook-2"></i>
            {{ node.label }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('please enter模版名称')"
            v-model="searchWord"
            @keyup.enter.native="hanleSearch"
            size="mini"
          >
            <el-button
              @click.native="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
          <el-button-group
            ><l-file-import
              fileType="json"
              classname="wfSchemeImport"
              @success="exportSuccess()"
            ></l-file-import
          ></el-button-group>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="columns"
        :dataSource="tableData"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_CreateDate="scope">
          {{ lr_dateFormat(scope.row.f_CreateDate) }}
        </template>
        <template v-slot:f_Category="scope">
          {{ lr_dataItemName(lr_dataItem["FlowSort"], scope.row.f_Category) }}
        </template>
        <template v-slot:f_EnabledMark="scope">
          <el-tag v-if="scope.row.f_Type != 1" size="mini">{{ $t('草稿') }}</el-tag>
          <el-switch
            v-else
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>
    <l-fullscreen-dialog
      :title="$t('流程模版设计')"
      :visible.sync="formVisible"
      @ok="handleSave"
      @closed="handleClosed"
      @opened="handleOpened"
      ref="formDialog"
    >
      <template #headerRight>
        <el-button @click="handleSaveDraft()" type="warning" size="mini"
          >{{$t('暂存')}}</el-button
        >
      </template>
      <my-form ref="form" > </my-form>
    </l-fullscreen-dialog>
    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="classifysVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="FlowSort"></l-dataitem-index>
    </l-drawer>

    <l-drawer
      :title="`${$t('历史记录')}-${$t(historyTitle)}`"
      :visible.sync="historyVisible"
      :showOk="false"
      :showClose="false"
      size="640px"
    >
      <history
        :schemeInfoId="schemeInfoId"
        :schemeId="schemeId"
        :updateSchemeId="updateSchemeId"
      ></history>
    </l-drawer>
  </l-layout>
</template>

<script>
const api = window.$api.workflow.scheme;
import MyForm from "./form";
import history from "./history";
export default {
  components: {
    MyForm,
    history,
  },
  data() {
    return {
      lr_isPage: true,
      // 左侧树形
      classifysVisible: false,
      treeCategory: "",

      // 搜索
      searchWord: "",

      // 表格
      columns: [
        { label: "编号", prop: "f_Code", minWidth: "150" },
        { label: "名称", prop: "f_Name", minWidth: "150" },
        { label: "分类", prop: "f_Category", width: "120", align: "center" },
        { label: "状态", prop: "f_EnabledMark", width: "64", align: "center" },
        {
          label: "创建人",
          prop: "f_CreateUserName",
          width: "100",
          align: "center",
        },
        { label: "创建时间", prop: "f_CreateDate", width: "160" },
      ],
      tableBtns: [
        { prop: "Edit", label: "Edit",width:40 },
        { prop: "Delete", label: "Delete",width:40 },
        { prop: "Copy", label: "复制",width:40 },
        { prop: "Export", label: "导出",width:40 },
        { prop: "History", label: "历史记录", width: 60 },
      ],
      tableLoading: false,
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableData: [],

      formVisible: false,
      formEditRow: null,
      formEdit: false,

      historyVisible: false,
      historyTitle: "",
      schemeInfoId: "",
      schemeId: "",

      formCopy:false//复制操作
    };
  },
  computed: {
    dataItemTree_FlowSort() {
      return this.lr_dataItemTree(this.lr_dataItem["FlowSort"]);
    },
  },
  mounted() {
    this.lr_loadDataItem("FlowSort");
    this.loadTablePage();
  },
  methods: {
    loadTablePage(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC",
        keyword: this.searchWord,
        category: this.treeCategory,
      };
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          this.tableData = data.rows;
          this.tableTotal = data.records;

          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePage(true);
    },

    // 搜索
    hanleSearch() {
      this.loadTablePage();
    },

    // 分类
    handleNodeClick(node) {
      this.treeCategory = node.value;
      this.tableCurrentPage = 1;
      this.loadTablePage();
    },
    handleSettingClick() {
      this.classifysVisible = true;
    },

    // 表单
    handleAdd() {
      this.formEdit = false;
      this.formVisible = true;
      this.formCopy = false;
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.formVisible = true;
      this.formCopy = false;
    },
    handleExport($index, row) {
      this.lr_downTempFile(
        `workflow/scheme/download/workflow/${row.f_Id}`,
        `流程_${row.f_Name}${row.f_Code}`,
        "workflow",
        "json"
      );
    },

    handleHistory($index, row) {
      this.formEditRow = row;
      this.historyTitle = row.f_Name;
      this.schemeId = row.f_SchemeId;
      this.schemeInfoId = row.f_Id;
      this.historyVisible = true;
    },
    updateSchemeId(id) {
      this.schemeId = id;
      this.formEditRow.f_SchemeId = id;
    },

    handleDelete($index, row) {
      this.$confirm(this.$t("This operation will permanently delete the data. Do you want to continue?"), this.$t("Tips"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning",
      })
        .then(() => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          api.remove(row.f_Id).then(() => {
            this.$message({
              type: "success",
              message: this.$t("Delete  success"),
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled"),
          });
        });
    },
    handleEnableChange(row) {
      api.updateState(row.f_Id, row.f_EnabledMark).then(() => {
        this.$message({
          type: "success",
          message: this.$t("更新成功!"),
        });
      });
    },
    handleSaveDraft() {
      this.handleSave(
        this.$refs.formDialog.showLoading,
        this.$refs.formDialog.hideLoading,
        true
      );
    },
    async handleSave(showLoading, hideLoading, isDraft) {
      showLoading("saving data...");
      if (!(await this.$refs.form.validateForm())) {
        hideLoading();
        return;
      }

      // 保存草稿
      let dto = this.$refs.form.getForm();
      dto.scheme.f_Type = isDraft ? 2 : 1; // 草稿

      if (this.formEdit) {
        api
          .update(this.formEditRow.f_Id, dto)
          .then(() => {
            this.loadTablePage();
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
            if (!isDraft) {
              this.formVisible = false;
            }
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        api
          .add(dto)
          .then(() => {
            this.loadTablePage();
            this.$message({
              type: "success",
              message: this.$t("save success!"),
            });
            this.formVisible = false;
            hideLoading();
          })
          .catch(() => {
            hideLoading();
          });
      }
    },

    async handleOpened(showLoading, hideLoading) {
      if (this.formEdit||this.formCopy) {//Edit
        showLoading("Loading data...");

        const data = await this.$awaitWraper(api.get(this.formEditRow.f_Code));

        if (this.formCopy) {
          data.scheme.f_Id = "";//流程模板
          data.scheme.f_SchemeInfoId="";//流程模板
          data.schemeinfo.f_ModuleId = "";//流程模板信息
          data.schemeinfo.f_SchemeId="";//流程模板信息
          if(data.schemeAuthList){
            data.schemeAuthList.forEach(item=>{
              item.f_Id="";
              item.f_SchemeInfoId="";
            })
          }
          data.schemeinfo.f_Code = `${data.schemeinfo.f_Code}-copy`;
          data.schemeinfo.f_Name = `${data.schemeinfo.f_Name}-复制`;
        }

        this.$refs.form.setForm(data);
        hideLoading();
      } else {
        this.$nextTick(() => {
          this.$refs.form.resetForm();
        });
      }
    },
    handleClosed() {
      this.$refs.form.resetForm();
    },

    //流程设计的复制
    handleCopy($index, row) {
      this.formEdit = false;
      this.formCopy = true;
      this.formEditRow = row;
      this.showForm();
    },
    showForm() {
      this.formVisible = true;
    },
    exportSuccess(){
          this.loadTablePage();
      },
  },
};
</script>